package com.hcg.multiplydatasource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

//import org.mybatis.spring.annotation.MapperScan;

/**
 * 读取 DataSource 数据源
 */
@Configuration  // 注册到 spring 容器中
// 扫包范围
@MapperScan(basePackages = "com.hcg.multiplydatasource.mapper.cmmapper",sqlSessionFactoryRef = "cmSqlSessionFactory")
public class CmDataSourceConfig {

    @Bean(name = "cmDataSource")
//    @Qualifier("cmDataSource") // 依赖注入时候的名字
    @ConfigurationProperties(prefix="spring.datasource.cm") // 扫描application 配置文件时的前缀
//    @Primary
    public DataSource cmDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "cmSqlSessionFactory")
//    @Primary
    public SqlSessionFactory cmSqlSessionFactory(@Qualifier("cmDataSource") DataSource cmDataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(cmDataSource);
        // 加载 mapper 对应的 xml 文件，如果没有可以注释掉
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mappers/cm/*.xml")
        );
        return bean.getObject();
    }

    @Bean(name = "cmTransactionManager")
//    @Primary
    public DataSourceTransactionManager cmTransactionManager(@Qualifier("cmDataSource") DataSource dataSource) throws Exception{
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "cmSqlSessionTemplate")
//    @Primary
    public SqlSessionTemplate cmSqlSessionTemplate(@Qualifier("cmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}